package com.ilas.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.ilas.entity.SysTenant;
import com.ilas.entity.TenantInfo;
import com.ilas.service.ITenantInfoService;
import com.ilas.service.ITenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * 初始化动态数据源
 * @author Luzck
 * @date 2019/11/06
 */
@Slf4j
@Configuration
public class DynamicDataSourceInit {

    @Resource
    private ITenantInfoService tenantInfoService;

    @Resource
    private ITenantService tenantService;

    @Resource
    private DynamicDataSource dynamicDataSource;

    @Value("${tenant.version}")
    private String tv;

    /**
     * 旧版-
     * @throws SQLException e
     */
    @PostConstruct
    public void initDataSource() throws SQLException {
        log.info("=====初始化动态数据源=====");

        if (StringUtils.isEmpty(tv)) {
            tv = "v1.0";
        }
        log.info("---------租户配置版本号：{}", tv);

        if ("v1.0".equals(tv)) {
            //加载master数据源除外的其他数据源
            List<TenantInfo> tenantList = tenantInfoService.findList();
            for (TenantInfo tenantInfo : tenantList) {
                log.info(tenantInfo.toString());
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setDriverClassName(tenantInfo.getDataSourceDriver());
                dataSource.setUrl(tenantInfo.getDataSourceUrl());
                dataSource.setUsername(tenantInfo.getDataSourceUsername());
                dataSource.setPassword(tenantInfo.getDataSourcePassword());
                dataSource.init();
                dynamicDataSource.setDataSources(tenantInfo);
            }
        } else {
            //加载master数据源除外的其他数据源
            List<SysTenant> tenantList = tenantService.queryAll();
            for (SysTenant tenant : tenantList) {
                dynamicDataSource.setDataSources(tenant);
            }
        }

    }

}
